package com.gogowan.agroenterprise.base;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.utils.PalUtils;

import java.lang.ref.WeakReference;

/**
 * @Description: 带标题的Activity
 * @author mdp
 * @date 2017年1月3日 上午11:22:33
 */
public abstract class TitleActivity extends BaseActivity implements View.OnClickListener{

	private boolean isDestroyed = false;
    private long timeStamp = 0;
    private long exitTime = 0;
    private boolean isExitTwice = false;
    private boolean isShowExitDialog = false;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setContentViewID());
        timeStamp = savedInstanceState == null ? System.currentTimeMillis() : savedInstanceState.getLong("timeStamp", System.currentTimeMillis());
        if(initData(getIntent(), savedInstanceState)){
            initView();
        }else {
            finish();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putLong("timeStamp",timeStamp);
        PalUtils.showLogE(this.getLocalClassName(),"onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }

    /**
     * 1.界面布局ID
     * */
    protected abstract int setContentViewID();

    /**
     * 2.初始化Data
     *
     * @param intent
     * @param savedInstanceState
     * */
    protected abstract boolean initData(Intent intent, Bundle savedInstanceState);

    /**
     * 3.初始化View
     * */
    protected abstract void initView();
    
    /**
     * 4.初始化Title
     * 
     * @param title
     * @param isShowRight
     */
    protected void initTitle(String title, boolean isShowRight) {
        ((TextView) findViewById(R.id.all_top_title)).setText(title);
        findViewById(R.id.all_top_back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.all_top_right_im).setVisibility(isShowRight ? View.VISIBLE : View.GONE);
    }

    protected void initTitle(String title, boolean isShowRight, int ImageId, final OnRightListener listener) {
        ((TextView) findViewById(R.id.all_top_title)).setText(title);
        findViewById(R.id.all_top_back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ImageView all_top_right_im = (ImageView) findViewById(R.id.all_top_right_im);
        all_top_right_im.setImageResource(ImageId);
        all_top_right_im.setVisibility(isShowRight ? View.VISIBLE : View.GONE);
        all_top_right_im.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClick();
            }
        });
    }
    public interface OnRightListener{
        void onClick();
    }
    /**
     * 通过泛型来简化findViewById
     *
     * @param id
     */
    protected final <E extends View> E getView(int id) {
        try {
            return (E) findViewById(id);
        } catch (ClassCastException ex) {
            throw ex;
        }
    }

    /**
     * @return Activity id
     **/
    protected long getTimeStamp(){
        return timeStamp;
    }
    
    /**
     * 是否应该是销毁状态
     * */
    public boolean isAlreadyDestroyed() {
		return isFinishing() || isDestroyed;
	}
    
    /**
     * 进度条
     * */
    protected void showProgressDialog(String msg){
    	hideProgressDialog();
    	progressDialog = new ProgressDialog(this);
    	progressDialog.setTitle(R.string.alert_title);
    	progressDialog.setOnCancelListener(new OnCancelListener(){

			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				finish();
			}
    		
    	});
    	progressDialog.setMessage(msg);
    	progressDialog.setCanceledOnTouchOutside(false);
    	progressDialog.setCancelable(true);
    	progressDialog.show();
    }
    
    /**
     * 进度条
     * */
    protected void hideProgressDialog(){
    	if(progressDialog != null){
    		progressDialog.dismiss();
    	}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PalUtils.showLogE(this.getLocalClassName(), "onActivityResult" +
                "requestCode = " + requestCode + "resultCode = " + resultCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PalUtils.showLogE(this.getLocalClassName(),"onDestroy");
        isDestroyed = true;
        weakRefHandler.removeCallbacksAndMessages(null);
        weakRefHandler = null;
    }

    /**
     * 二次返回
     */
    public void setIsExitTwice(boolean isExitTwice) {
        this.isExitTwice = isExitTwice;
    }

    /**
     * 返回提示
     */
    public void setIsShowExitDialog(boolean isShowExitDialog) {
        this.isShowExitDialog = isShowExitDialog;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isExitTwice) {
            goBack();
            if (isShowExitDialog) {
                showExitDialog();
            }
            return false;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && isShowExitDialog) {
            showExitDialog();
            if (isExitTwice) {
                goBack();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出
     */
    public void goBack() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            PalUtils.showShortToast(getApplicationContext(),"再按一次返回");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    /**
     * goBack
     */
    public void showExitDialog() {

    }

    @Override
    public void onClick(View v) {
        if (PalUtils.isDClick()) {
            return;
        }
        onClicked(v);
    }

    /**
     * 点击事件处理
     *
     * @param v
     * */
    protected abstract void onClicked(View v);

    /**WeakRefHandler*/
    private WeakRefHandler weakRefHandler = new WeakRefHandler(this);

    /**
     * handler回调
     *
     * @param activity
     * @param msg
     * */
    public abstract void handleMessage(TitleActivity activity, android.os.Message msg);

    /**
     * WeakRefHandler
     */
    public static class WeakRefHandler extends Handler {

        private WeakReference<TitleActivity> weakRefActivity;

        public WeakRefHandler(TitleActivity activity) {
            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            if (weakRefActivity.get() == null) {
                return;
            }
            weakRefActivity.get().handleMessage(weakRefActivity.get(),msg);
        }
    }

    /**
     * getWeakRefHandler
     * */
    public WeakRefHandler getWeakRefHandler(){
        return weakRefHandler;
    }
}
